package art.client.activites;

import java.util.List;

import art.client.ClientFactory;
import art.client.ClientUtils;
import art.client.views.UsersListView;
import art.shared.entities.LoginInfo;
import art.shared.entities.UserShared;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class UsersListActivity extends AbstractActivity {

	private ClientFactory clientFactory = null;
	private LoginInfo loginInfo = null;

	public UsersListActivity(ClientFactory clientFactory, LoginInfo loginInfo) {
		this.clientFactory = clientFactory;
		this.loginInfo = loginInfo;
	}

	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		initView(containerWidget);
	}

	private void initView(final AcceptsOneWidget containerWidget) {
		if (loginInfo == null) {
			ClientUtils.getUserService().getLoginInfo(
					new AsyncCallback<LoginInfo>() {

						@Override
						public void onSuccess(LoginInfo loginInfo) {
							executeInit(containerWidget);
						}

						@Override
						public void onFailure(Throwable arg0) {

						}
					});
		} else {
			executeInit(containerWidget);
		}
	}

	private void executeInit(final AcceptsOneWidget containerWidget) {
		UsersListView usersView = clientFactory.getUsersListView(loginInfo);
		containerWidget.setWidget(usersView.asWidget());
		getUsersAndUpdateTable(usersView);
	}

	private void getUsersAndUpdateTable(final UsersListView usersView) {
		ClientUtils.getUserService().getUsers(
				new AsyncCallback<List<UserShared>>() {
					public void onFailure(Throwable error) {
					}

					public void onSuccess(List<UserShared> result) {
						usersView.updateTable(result);
					}
				});
	}

}
